<template>
    <div class="title">
        空气环境公众监督系统
        <!-- <el-button type="success" @click="router.replace('/nepm')">nepm管理员</el-button>
        <el-button type="success" @click="router.push('/nepg')">nepg网格员</el-button>
        <el-button type="success" @click="router.push('/neps')">neps公众监督员</el-button> -->
    </div>

    <div class="login-view">
        <div class="login-container" :style="{ backgroundImage: `url(${backgrounds[bgIndex]})` }">
            <el-card class="login-card" v-if="showLoginView">
                <h1 class="login-title">用户登录</h1>
                <el-form ref="loginFormRef" :model="loginForm" @keyup.enter.native="login" :rules="loginRules"
                    label-position="top" class="login-form">
                    <el-form-item label="邮箱" prop="username">
                        <el-input v-model="loginForm.username" />
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input type="password" v-model="loginForm.password" show-password />
                    </el-form-item>
                    <el-form-item label="验证码" prop="captcha">
                        <el-input style="width: 30%;" v-model="loginForm.captcha"></el-input>
                        <img :src="captchaImg" alt="" class="captcha" @click="getCaptcha()">
                    </el-form-item>
                </el-form>
                <el-button type="primary" class="loginBtn" @click="login" @keyup="login">登录</el-button>
                <el-button link type="primary" @click="showLoginView = false" class="register"
                    style="margin-top: 5px;">注册成为公众监督员</el-button>
            </el-card>
            <el-card class="register-card" v-else>
                <h1 class="register-title">用户注册</h1>
                <el-form label-position="right" label-width="80px" :model="registerForm" ref="registerFormRef"
                    class="register-form" :rules="registerRules">
                    <el-form-item label="邮箱" prop="username">
                        <el-input v-model="registerForm.username" type="email" />
                    </el-form-item>
                    <el-form-item label="手机号码" prop="phone">
                        <el-input v-model="registerForm.phone" />
                    </el-form-item>
                    <el-form-item label="城市" prop="city">
                        <div class="city-border">
                            <chooseCity style="width: 100%;height: 100%;" @changeCity="changeCity"
                                @changeProvince="changeProvince" @clear="registerForm.city = ''"></chooseCity>
                        </div>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input type="password" v-model="registerForm.password" show-password />
                    </el-form-item>
                    <el-form-item label="确认密码" prop="conPwd">
                        <el-input type="password" v-model="registerForm.conPwd" show-password />
                    </el-form-item>
                </el-form>
                <div class="btns">
                    <el-button type="primary" class="btn" @click="register">立即注册</el-button>
                    <el-button type="primary" class="btn" @click="showLoginView = true">返回登录</el-button>
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { inject, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import chooseCity from "../components/common/chooseCity.vue";
import bg1 from '../assets/images/1.jpg'
import bg2 from '../assets/images/2.jpg'
import bg3 from '../assets/images/3.jpg'
import bg4 from '../assets/images/4.jpg'
import bg5 from '../assets/images/5.jpg'

import { get, post, getUUID } from '../utils/index.ts'

const cookies = inject('$cookies') as any
import { useRouter } from 'vue-router'
const router = useRouter()

const Message = inject('$message') as any

const loginFormRef = ref(null)
const registerFormRef = ref(null)

const backgrounds = [bg1, bg2, bg3, bg4, bg5]
let timer: ReturnType<typeof setInterval>
const showLoginView = ref(true)
const bgIndex = ref(0)

let uuid: string = ''
let captchaImg: any = ref(null)
const getCaptcha = async () => {
    uuid = getUUID()
    let data: object = {
        uuid,
    }
    let res: any = await get('/captcha.jpg', data, 'blob')
    captchaImg.value = window.URL.createObjectURL(res)
}

onMounted(() => {
    getCaptcha()
    // timer = setInterval(() => {
    //     if (bgIndex.value >= backgrounds.length - 1) {
    //         bgIndex.value = 0
    //     }
    //     else {
    //         bgIndex.value++
    //     }
    // }, 8000)
})
onBeforeUnmount(() => {
    // clearInterval(timer)
})
interface LoginForm {
    username: string
    password: string
    captcha: string
}
const loginForm = reactive<LoginForm>({
    username: '',
    password: '',
    captcha: '',
})
interface RegisterForm {
    username: string
    password: string
    conPwd: string
    phone: string
    city: string,
}
const registerForm = reactive<RegisterForm>({
    username: '',
    password: '',
    phone: '',
    conPwd: '',
    city: '',
})

const validEmail = (rule: any, value: any, callback: any) => {
    if (!value) {
        return callback(new Error('请输入邮箱'))
    } else {
        if (isValidUsername(value)) {
            return callback(new Error('邮箱不应为中文'))
        } if (!validateEmail(value)) {
            return callback(new Error('邮箱格式错误'))
        }
    }
    callback()
}

const validatePhone = (rule: any, value: any, callback: any) => {
    const phoneReg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    if (!value) {
        return callback(new Error('手机号码不能为空'))
    }
    if (!Number.isInteger(+value.trim())) {
        callback(new Error('请输入数字'))
    } else {
        if (phoneReg.test(value)) {
            callback()
        } else {
            callback(new Error('手机号码格式不正确'))
        }
    }
};

const validPassword = (rule: any, value: any, callback: any) => {
    if (value === '') {
        return callback(new Error('请输入密码'))
    } else {
        callback()
    }

}
const validPassword2 = (rule: any, value: any, callback: any) => {
    if (value === '') {
        return callback(new Error('请再次输入密码'))
    } else if (value !== registerForm.password) {
        callback(new Error('两次输入的密码不相同'))
    } else {
        callback()
    }

}


const loginRules = ref({
    username: [{ required: true, validator: validEmail, trigger: 'blur' }] as Array<object>,
    password: [{ required: true, validator: validPassword, trigger: 'blur' }] as Array<object>,
    captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
})
const registerRules = ref({
    username: [{ required: true, validator: validEmail, trigger: 'blur' }],
    phone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
    password: [{ required: true, validator: validPassword, trigger: 'blur' }],
    conPwd: [{ required: true, validator: validPassword2, trigger: 'blur' }],
    city: [{ required: true, message: '请选择你的城市', trigger: 'blur' }],
})

function isValidUsername(email: string) {
    const pattern = /[\u4e00-\u9fa5]/; // 匹配中文字符
    return pattern.test(email);
}
function validateEmail(email: string) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

const changeCity = (e: any) => {
    registerForm.city = e.name
}
const changeProvince = (e: any) => {
    registerForm.city = e
}

const login = async () => {
    const form = loginFormRef as any
    let params: object = {
        // username: loginForm.username,
        // password: loginForm.password,
        ...loginForm,
        uuid: uuid,
    }

    form.value.validate(async (valid: boolean) => {
        if (valid) {
            let res: any = await post('/sys/login', params)
            if (res && res.code === 0) {
                cookies.set('token', res.token)
                cookies.set('username', res.userName)
                cookies.set('identity', res.identity)
                Message.success('登录成功')
                if (res.identity === 2) {
                    router.push('/nepm')
                } else if (res.identity === 1) {
                    router.push('/nepg')//网格员
                } else if (res.identity === 0) {
                    router.push('/neps')//监督员
                } else {
                    Message('未收到身份参数，请联系管理员')
                }
            } else {
                getCaptcha()
                loginForm.password = ''
                Message(`msg:${res.msg};code:${res.code}`)
            }
        } else {
            Message.info('表单校验失败')
        }
        return valid
    })



}
const register = async () => {
    const form = registerFormRef as any
    let params: object = {
        ...registerForm,
        mobile: registerForm.phone,
        cityName: registerForm.city + '市'
    }
    form.value.validate(async (valid: boolean) => {
        if (valid) {
            let res: any = await post('/sys/save', params)
            if (res && res.code === 0) {
                Message.success(`注册成功`)
                showLoginView.value = true
            } else {
                Message(`msg:${res.msg};code:${res.code}`)
            }
        } else {
            Message.info('注册表单校验失败')
            return false
        }
    })

}

</script>

<style lang="scss" scoped>
.title {
    position: absolute;
    top: 80px;
    left: 150px;
    color: #ffdaa2;
    font-weight: 600;
    font-size: $large-size;
    // background-color: #999;
}

.city-border {
    height: 30px;
    padding: 0 10px;
    border: 1px solid #999;
    border-radius: 5px;
}

.login-view {

    width: 100vw;
    height: 100vh;

    .login-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
        background-color: $home-bgc;
        // opacity: ;
        transition: all 800ms;

        .captcha {
            margin: 0 20px;
            width: 160px;
        }

        .login-card:hover {
            filter: drop-shadow(0 0 1em #32ca99);
        }

        .register-card:hover {
            filter: drop-shadow(0 0 1em #32ca99);
        }

        .register-card {
            width: 400px;
            min-height: 300px;
            will-change: filter;
            transition: all 300ms;
            opacity: 0.9;
            background-color: #f2f3f5;
            border-radius: 20px;

            .register-title {
                text-align: center;
                font-size: 24px;
                margin-bottom: 20px;
                color: #32ca99;
            }

            .btns {
                text-align: center;

                .btn {
                    background-color: #32ca99;
                    border-color: #32ca99;
                }
            }
        }

        .login-card {
            width: 400px;
            min-height: 300px;
            will-change: filter;
            transition: all 300ms;
            opacity: 0.9;
            background-color: #f2f3f5;
            border-radius: 20px;

            .login-title {
                text-align: center;
                font-size: 24px;
                margin-bottom: 20px;
                color: #32ca99;
            }

            .login-form {
                margin-top: 20px;
            }

            .loginBtn {
                display: block;
                margin: 0 auto;
                background-color: #32ca99;
                border-color: #32ca99;
            }

            .register {
                display: block;
                margin: 0 auto;
            }
        }
    }
}
</style>